package com.mengdie.shuidi.ui.interfaces;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.common.ClientConfig;
import com.mengdie.shuidi.model.BaseModelOne;
import com.mengdie.shuidi.model.PayEntity;
import com.mengdie.shuidi.utils.PayResult;
import com.mengdie.shuidi.utils.ToastUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/3/21 10:45
 * 邮箱：hqy_xz@126.com
 */

public class PayHelper extends MDPresenter {

    private static final int SDK_PAY_FLAG = 1;

    private PayView payListener;


    private Activity mActivity;

    private String type;

    private IWXAPI api;


    public PayHelper(Activity activity, PayView listener) {

        this.mActivity = activity;
        this.payListener = listener;

        api = WXAPIFactory.createWXAPI(activity.getApplicationContext(), ClientConfig.WX_APP_ID);
        api.registerApp(ClientConfig.WX_APP_ID);
    }


    public void setOrder(String order, String type) {
        this.type = type;
        if (type.equals("1")) {
            getAlipaySign(order);
        } else {
            getWxpaySign(order);
        }

    }


    public void getAlipaySign(String orderId) {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(mActivity))
                .post(AppContext.getInstance().getPayUrl() + "core/unionpay/api_ali_sign")
                .tag("pay")
                .params("order_id", orderId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        Gson gson = new Gson();
                        Type payType = new TypeToken<PayEntity>() {
                        }.getType();
                        PayEntity pay = gson.fromJson(s, payType);

                        onPayScc(pay);
                    }
                });
    }

    public void getWxpaySign(String orderId) {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(mActivity))
                .post(AppContext.getInstance().getPayUrl() + "core/unionpay/water_api_wx_sign")
                .tag("pay")
                .params("order_id", orderId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type payType = new TypeToken<BaseModelOne<PayEntity>>() {
                        }.getType();

                        BaseModelOne<PayEntity> payBase;
                        try {
                            payBase = gson.fromJson(s, payType);
                        } catch (JsonSyntaxException e) {
                            payBase = gson.fromJson(s, BaseModelOne.class);
                        }
                        if (payBase.getRet().equals("0")) {
                            PayEntity pay = payBase.getMsg();
                            onPayScc(pay);
                        }

                    }
                });
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        payListener.paySucc();
                        ToastUtil.showToast(mActivity.getResources().getString(R.string.pay_success));
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtil.showToast(mActivity.getResources().getString(R.string.pay_in));
                            payListener.payFial();
                        } else if (TextUtils.equals(resultStatus, "4000")) {
                            ToastUtil.showToast(mActivity.getResources().getString(R.string.pay_fial));
                            payListener.payFial();
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            ToastUtil.showToast(mActivity.getResources().getString(R.string.pay_cancel_fial));
                            payListener.payFial();
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            ToastUtil.showToast(mActivity.getResources().getString(R.string.pay_network_fial));
                            payListener.payFial();
                        } else if (TextUtils.equals(resultStatus, "6004")) {
                            ToastUtil.showToast(mActivity.getResources().getString(R.string.pay_handle_fial));
                            payListener.payFial();
                        } else {
                            ToastUtil.showToast(mActivity.getResources().getString(R.string.pay_other_fial));
                            payListener.payFial();
                        }
                    }

                    break;
                }
                default:
                    break;
            }
        }

    };


    public void onPayScc(final PayEntity payEntity) {
        if (type.equals("2")) {
            PayReq req = new PayReq();
            req.appId = payEntity.getAppid();
            req.partnerId = payEntity.getPartnerid();
            req.prepayId = payEntity.getPrepayid();
            req.nonceStr = payEntity.getNoncestr();
            req.timeStamp = String.valueOf(payEntity.getTimestamp());
            req.packageValue = "Sign=WXPay";
            req.sign = payEntity.getSign();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        } else if (type.equals("1")) {
            final String orderinfo = payEntity.getSign();
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(mActivity);
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(orderinfo, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }

    @Override
    public void onDestory() {
        OkGo.getInstance().cancelTag("pay");
        payListener = null;
        mActivity = null;
    }
}
